﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GHRMS.APP.Classes;
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PS_Retirements : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        private IRetirementBLL rtBLL = new RetirementBLL();
        private RetirementDetailBLL rtDtlBLL = new RetirementDetailBLL();
        private RadComboBox cmbEmployeeType;
        private Main main = new Main();

        protected void Page_Load(object sender, EventArgs e)
        {
            // Export
            if(!Page.IsPostBack && main.ConvertNullInt(Request["Sequence"]) != null)
            {
                int retirementSeq = main.ConvertNullInt(Request["Sequence"]).Value;

                ExportWord(retirementSeq);
                return;
            }
            // UI
            cmbEmployeeType = (RadComboBox)cbEmployeeType.FindControl("cbEmployeeType");

            if (!Page.IsPostBack)
            {
                cbEmployeeType.ListEmployeeTypeComboBox();
                //LoadDataGrid();
            }
        }

        private void ExportWord(int retirementSeq)
        {
            MailMerge mailMerge = new MailMerge();
            var field = new Dictionary<string, string>();
            var table = new List<Dictionary<string, string>>();
            // Data
            {
                DataRow dr = rtBLL.LoadRetirements(retirementSeq, null).Tables[0].Rows.Cast<DataRow>().FirstOrDefault(dri => main.ConvertNullInt(dri[0]) == retirementSeq);
                DataTable dt = rtDtlBLL.LoadRetirementDetails(null, retirementSeq).Tables[0];
                /*job_site_name JobSiteName
                Row.Count = MCount
                ref_no = CommandCode
                approved_date = ReportDate
                start_date  = EffectiveDate
                EmployeeList
                ลำดับที่ ชื่อสกุล สังกัด ตำแหน่ง*/
                field.Add("JobSiteName", Convert.ToString(dr["job_site_name"]));
                field.Add("MCount", dt.Rows.Count.ToString());
                field.Add("CommandCode", Convert.ToString(dr["ref_no"]));
                field.Add("CommandTitle", Convert.ToString(dr["retire_title"]));
                DateTime? dtRetireDate = main.ConvertNullDateTime(dr["approved_date"]);
                DateTime? dtEffectiveDate = main.ConvertNullDateTime(dr["start_date"]);
                field.Add("ReportDate", dtRetireDate.HasValue ? dtRetireDate.Value.ToString("d MMMM yyyy") : string.Empty);
                field.Add("EffectiveDate", dtEffectiveDate.HasValue ? dtEffectiveDate.Value.ToString("d MMMM yyyy") : string.Empty);
                string employeeList = "";
                int i = 1;
                string space = "                                            ";
                foreach(DataRow dri in dt.Rows)
                {
                    // "ลำดับที่    ชื่อสกุล   สังกัด    ตำแหน่ง"
                    employeeList += "" + (i++) + space + dri["FULL_NAME"] + space + dri["JOB_SITE_NAME"] + space + dri["POS_REF"]+"-" + dri["POS_NAME"]  + "\r\n";
                }
                field.Add("EmployeeList", employeeList);
            }
            var filename = "ประกาศเกษียณอายุ" + DateTime.Now.ToString("yyMMddHHmmss") + ".docx";
            var filePath = Server.MapPath("~/Reports/Temp/");
            var fileTemplateName = Server.MapPath("~/Reports/Templates/ประกาศเกษียณอายุ.docx");
            if( mailMerge.MergeTemplate(fileTemplateName, filePath + filename, field, null, table))
            {
                mailMerge.SaveFileToClient(Response, filePath, filename, false);
            }
            
        }

        public void LoadDataGrid()
        {
            Nullable<int> EmployeeType = string.IsNullOrEmpty(cmbEmployeeType.SelectedValue) ? null : (Nullable<int>)Convert.ToInt32(cmbEmployeeType.SelectedValue);

            DataSet ds = rtBLL.LoadRetirements((int?)null, EmployeeType);
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                RadGrid1.DataSource = dt;
                RadGrid1.DataBind();
            }
        }
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["RETIRE_SEQ"]);
                rtBLL.Delete(seq, ssMng.EmpSeqI);
            }

            LoadDataGrid();
        }

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                DataRowView DataRow = (DataRowView)e.Item.DataItem;
                Session["RETIREYEAR"] = DataRow["RETIRE_YEAR"].ToString();
            }
        }

        protected void cmdFilter_Click(object sender, EventArgs e)
        {
            Session["EMPTYPE"] = cmbEmployeeType.SelectedValue.ToString();
            LoadDataGrid();
            //}
        }

    }

}
